package com.baozi.product.service;

import com.baozi.product.DTO.CartDto;
import com.baozi.product.entity.product;
import com.baozi.product.enumes.ProdutcStatusEnum;
import com.baozi.product.enums.ResultEnum;
import com.baozi.product.exception.ProductException;
import com.baozi.product.repository.ProductRepository;
import com.baozi.product.vo.ProductVo;
import com.baozi.product.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

@Service
public class productService {

    @Autowired
    ProductRepository productRepository;


    public List<product> findUpAll(){
       return  productRepository.findByProductStatus(ProdutcStatusEnum.UP.getCode());
    }


    public List<product> list(List<String> ids){
        return productRepository.findByProductIdIn(ids);
    }

    @Transactional
    public void deleteStock(List<CartDto> list){
        for(CartDto dto:list){
            Optional<product> productOptional=productRepository.findById(dto.getProductId());
            //判断商品是否存在
            if(!productOptional.isPresent()){
                throw new ProductException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            //判断库存是否足够
            product pro=productOptional.get();
            Integer num=pro.getProductStock()-dto.getProductQuantity();
            if(num<0){
                throw new ProductException(ResultEnum.PRODUCT_STOCK_ERROR);
            }
            pro.setProductStock(num);
            productRepository.save(pro);
        }
        //return
    }
}
